package org.mikhaylov.cp.service.command.impl;

import javax.servlet.http.HttpServletRequest;

import org.mikhaylov.cp.service.command.ServiceCommand;
import org.mikhaylov.cp.service.db.entities.User;
import org.mikhaylov.cp.service.hibernate.HibernateManager;
import org.mikhaylov.cp.service.response.Response;
import org.mikhaylov.cp.service.response.ResponseType;

public class LoginServiceCommand extends ServiceCommand {

	private static final long serialVersionUID = -5617855150538141832L;
	private String login = null;
	private String password = null;

	@Override
	protected boolean checkParams(HttpServletRequest request) {
		if (request.getAttribute("login") == null || request.getAttribute("password") == null
				|| !(request.getAttribute("login") instanceof String)
				|| !(request.getAttribute("password") instanceof String) ||
				((String)request.getAttribute("login")).isEmpty() || 
				((String)request.getAttribute("password")).isEmpty()) {
			Response response = new Response();
			response.setType(ResponseType.ERROR);
			response.setMeta("Wrong parameters");
			return false;
		}
		return true;
	}

	@Override
	protected boolean extractParams(HttpServletRequest request) {
		login = String.valueOf(request.getAttribute("login"));
		password = String.valueOf(request.getAttribute("password"));
		return true;
	}

	@Override
	protected void process(HttpServletRequest request) {
		User user = HibernateManager.getInstance().getUser(login, password);

		if (user == null) {
			response.setType(ResponseType.ERROR);
			response.setMeta("No user with such login/password combination");
			return;
		}

		request.setAttribute("user", user);
		response.setType(ResponseType.SUCCESS);
		response.setMeta("You have been successfully authorized");
	}

}
